<template>
  <div v-loading="loading">
    <common-page
      ref="common"
      :ccode="ccode"
      @hook:created="commonCreated"
    >
      <template #_rating="{form, conf, complexInstance, fullData}">
        <div>
          <p v-if="hasRatingForm" class="label">{{ ratingFormName }}</p>
          <complex-form2
            v-if="hasRatingForm"
            ref="ratingForm"
            :layout="ratingLayout"
            :res-data="ratingForm"
            :fields="ratingForm.tableInfo.fieldList"
            :data="ratingForm.data"
            :disabled="!!readonly"
            :field-rule="ratingForm.rule"
            :complex-config="ratingFormConfig"
          />
          <p v-if="hasRatingList" class="label">评分记录</p>
          <approve-history v-if="hasRatingList" :approval-list="ratingList" />
        </div>
      </template>
      <div class="form-info">
        <sticky :sticky-top="stickyTop" :z-index="100" class-name="btn-sticky" style="margin-bottom:10px">
          <approve-cmd v-if="!loading" :todo-info="todoInfo" :common-save="commonSave" :common-validate="commonValidate" @save="saveTodoForm" @submit="submitTodoForm" />
        </sticky>

        <div style="margin-top:30px;">
          <p class="label">审批表单</p>
          <complex-form2
            v-if="layout"
            ref="todoForm"
            :layout="layout"
            :res-data="customForm"
            :fields="customForm.tableInfo.fieldList"
            :flow-fileds="workFlowFields"
            :data="customForm.data"
            :disabled="!!readonly"
            :field-rule="customForm.rule"
            :complex-config="formConfig"
            is-flow
            :p-instance="this"
          />
          <p class="label" style="margin-top:12px;">审批历史</p>
          <approve-history :approval-list="approvalList" />
        </div>
      </div>
    </common-page>
  </div>
</template>

<script>
import {
  invokeMethod
} from '@/api/common'
import {
  saveWf
} from '@/api/workflow'
import ApproveHistory from '@/components/WorkFlow/approveHistory.vue'
import ApproveCmd from '@/components/WorkFlow/approveCmd.vue'
import Sticky from '@/components/Sticky/index.vue'
import { mapGetters } from 'vuex'
import {
  getUrlParam2,
  windowClose
} from '@/utils/index'

export default {
  name: 'WorkflowTodo',
  components: {
    ApproveHistory,
    ApproveCmd,
    Sticky
  },
  data() {
    return {
      activeName: 'form',
      customForm: {}, // 表单
      customPage: {}, // 页面
      layout: null,
      loading: true,
      todoInfo: {},
      approvalList: {},
      formConfig: {},
      ratingForm: {}, // 评分表单
      ratingFormConfig: {}, // 评分表单配置项
      ratingLayout: null, // 评分表单布局
      ratingList: null // 评分记录
    }
  },
  inject: ['reload'],
  computed: {
    ...mapGetters([
      'isShowNav'
    ]),
    ccode: function() {
      return this.$route.meta.code
    },
    oInsId: function() {
      return this.$route.query.parentDataId
    },
    readonly: function() {
      return this.todoInfo.readonly
    },
    allowSave: function() {
      return this.todoInfo.allowSave
    },
    allowSubmit: function() {
      return this.todoInfo.allowSubmit
    },
    navCode: function() {
      return this.customPage?.navCode || ''
    },
    options: function() {
      if (this.cmdForm.personId) {
        return [{
          label: this.cmdForm.personName,
          value: this.cmdForm.personId
        }]
      } else {
        return []
      }
    },
    stickyTop: function() {
      return this.isShowNav ? 90 : 0
    },
    hasRatingForm: function() {
      return !!this.ratingLayout
    },
    ratingFormName: function() {
      return this.ratingForm.name
    },
    hasRatingList: function() {
      return !!this.ratingList
    },
    // 流程字段
    workFlowFields: function() {
      return this.todoInfo.taskFieldModelList || []
    }
  },
  watch: {
    cmdVisible: function(visible) {
      if (visible) {
        setTimeout(() => {
          this.$refs.cmdMemo.focus()
        })
      } else {
        const oriForm = this.$options.data().cmdForm
        Object.keys(oriForm).forEach(key => {
          this.cmdForm[key] = oriForm[key]
        })
      }
    }
  },

  mounted: function() {
    this.getTodoInfo()
  },
  methods: {
    reloadForm() {
      this.getTodoInfo()
    },
    commonCreated() {

    },
    // 多表单校验
    commonValidate() {
      return new Promise((resolve, reject) => {
        const queue = [this.$refs.todoForm.formValidate()]
        if (this.hasRatingForm && this.$refs.ratingForm) {
          queue.push(this.$refs.ratingForm.formValidate())
        }
        Promise.all(queue).then(values => {
          const allValidate = values.every(i => i)
          if (allValidate) {
            resolve(true)
          }
        }).catch(errorFields=>{
          // 流程表单&评分表单未校验通过时定位到错误字段
          const firstKey = Object.keys(errorFields)[0]
          this.$refs.todoForm.scrollToField(firstKey)
          if(this.$refs.ratingForm){
            this.$refs.ratingForm.scrollToField(firstKey)
          }
        })
      })
    },
    // 字表保存
    saveSubTable() {
      if (this.$refs['todoForm']) {
        const subTables = this.$refs['todoForm'].getEditSubTables()
        if (subTables && subTables.length) {
          return Promise.all(subTables.map(item => item.saveSubTable()))
        }
      }
      return Promise.resolve()
    },
    /**
     * 1. 判断字表是否需要保存，优先保存字表数据
     * 2. 判断是否有评分模块，也需要进行保存
     */
    commonSave() {
      return new Promise((resolve) => {
        this.saveSubTable().then(() => {
          const todoForm = this.$refs.todoForm.getFullFormData()
          if (this.hasRatingForm && this.$refs.ratingForm) {
            todoForm._rating_data = JSON.stringify(this.$refs.ratingForm.getFullFormData())
          }
          const params = {
            oInsId: this.oInsId,
            cmdMemo: '',
            data: todoForm
          }
          saveWf(params).then(res => {
            if (res.success) {
              resolve()
            } else {
              this.$$message(res.message)
            }
          })
        })
      })
    },
    saveTodoForm() {
      this.commonValidate().then(() => {
        this.commonSave().then(() => {
          this.$$success('保存成功')
          this.reload()
        })
      })
    },
    submitTodoForm() {
      this.commonValidate().then(() => {
        this.commonSave().then(() => {
          const params = {
            methodId: '814519156803112960',
            data: {
              oInsId: this.oInsId
            }
          }
          invokeMethod(params).then(res => {
            if (res.success) {
              this.$$success(res.message)
              this.backList()
            } else {
              this.$$message(res.message)
            }
          }).finally(() => {
          })
        })
      })
    },
    // 返回列表页
    backList() {
      if (getUrlParam2('_layout') === '0,0') {
        windowClose()
        return
      }
      const view = this.$route
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        this.$router.back()
      })
    },
    // 获取代办事项
    getTodoInfo() {
      const params = {
        methodId: '773567309020139520',
        data: {
          oInsId: this.oInsId
        }
      }
      this.layout = null
      this.ratingLayout = null
      this.approvalList = {}
      invokeMethod(params).then(res => {
        this.todoInfo = res.data
        this.customForm = res.data.customForm || {}
        this.customPage = res.data.customPage || {}
        this.formConfig = this.customForm.form_config ? JSON.parse(this.customForm.form_config) : {}
        if (this.customForm?.layout) {
          this.layout = JSON.parse(this.customForm.layout)
        }
        this.approvalList = res.data.approvalList
        // 评分表单
        this.ratingForm = res.data.ratingForm || {}
        this.ratingFormConfig = this.ratingForm.form_config ? JSON.parse(this.ratingForm.form_config) : {}
        if (this.ratingForm?.layout) {
          this.ratingLayout = JSON.parse(this.ratingForm.layout)
        }
        this.ratingList = res.data.ratingList
      }).finally(() => {
        this.loading = false
      })
    }

  }
}
</script>
<style lang="scss" scoped>
p.label{
  font-size: 14px;
  font-weight: bold;
  margin: 8px 0;
}
.tool-container{
  text-align: right;
  margin-top: 10px;
  margin-right: 20px;
}
.approve-list{
  margin-top: 10px;
}
::v-deep .btn-sticky{
  background: #fff;
  box-sizing: content-box;
  transform: translateY(-6px);
  padding: 6px 0;
  height: fit-content !important;
}
</style>
